import { Inject, Provide } from "@midwayjs/decorator";
import { InjectEntityModel } from "@midwayjs/typegoose";
import { ReturnModelType } from "@typegoose/typegoose";
import { Docs } from "../entity/docs";
import { User } from "../entity/user";
import { RespInfo } from "../types/common.type";
import { RespMethod } from "../util/common.method";
import { ThumbService } from "./thumb.service";


@Provide()
export class DocsService {

  @InjectEntityModel(User)
  userModel: ReturnModelType<typeof User>;

  @InjectEntityModel(Docs)
  docsModel: ReturnModelType<typeof Docs>;

  @Inject()
  thumbService: ThumbService;

  /** 创建文库 */
  async add(useruid: string, remark: string, bgcolor: string): Promise<RespInfo> {
    const user = await this.userModel.findOne({ uid: useruid })
    const info = await this.docsModel.create({ user, remark, bgcolor })
    return RespMethod({ info })
  }

  /** 删除文章 */
  async delete(uid: string): Promise<RespInfo> {
    await this.docsModel.deleteOne({ uid })
    return RespMethod({})
  }

  /** 文章 list */
  async list(page: number = 0, number: number = 0, user?: string): Promise<RespInfo> {
    let list = [];
    let total = 0;
    if (user && false) {
      list = await this.docsModel.find({ user: { uid: user } }).populate('user', 'uid nick avatar').skip((page - 1) * number).limit(number).sort([['created', -1]])
      total = (await this.docsModel.find({ user: { uid: user } })).length;
    } else {
      list = await this.docsModel.find({}).populate('user', 'uid nick avatar').skip((page - 1) * number).limit(number).sort([['created', -1]])
      total = (await this.docsModel.find({})).length;
    }
    return RespMethod({ list, total, page: Math.ceil(total / number) })
  }

  /** get 文章 */
  async get(uid: string, user?: string): Promise<RespInfo> {
    const info = await this.docsModel.findOne({ uid }).populate('user', 'uid nick avatar');
    const thumbup = await this.thumbService.getCountByTarget(uid);
    const thumbtype = await this.thumbService.getThumbTypeByUser(uid, user);
    return RespMethod({ info: { ...(info as any)._doc, thumbup, thumbtype } })
  }

}